package cn.icanci.ladybird.common.util.task;

import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author: icanci
 * @date: Created in 2020/10/14 8:54
 * @classAction: 延时任务处理器
 */
public class DelayTask implements Delayed {
    /**
     * 业务数据
     */
    private final TaskBase data;
    /**
     * 任务延时时间
     */
    private final long expire;

    /**
     * 构造延时任务
     *
     * @param data   业务数据
     * @param expire 任务延时时间 （ms）
     */
    public DelayTask(TaskBase data, long expire) {
        this.data = data;
        this.expire = expire + System.currentTimeMillis();
    }

    public TaskBase getData() {
        return data;
    }

    public long getExpire() {
        return expire;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof DelayTask) {
            return this.data.getIdentifier().equals(((DelayTask) o).getData().getIdentifier());
        }
        return false;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("DelayTask{");
        sb.append("data=").append(data);
        sb.append(", expire=").append(expire);
        sb.append('}');
        return sb.toString();
    }

    @Override
    public int hashCode() {
        return Objects.hash(data, expire);
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expire - System.currentTimeMillis(), unit);
    }

    @Override
    public int compareTo(Delayed o) {
        long delta = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        return (int) delta;
    }
}
